package com.sx.micowell.framework.model

import android.annotation.SuppressLint
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.example.mvvm.base.data.MutableLiveListData
import com.example.mvvm.base.vm.BaseViewModel
import com.example.mvvm.rx.RxBus
import com.example.mvvm.until.LogUtils
import com.github.mikephil.charting.data.PieEntry
import com.miloyu.modelnet.cache.CacheBean
import com.miloyu.modelnet.network.ApiResponse
import com.miloyu.modelnet.network.BaseResponse
import com.miloyu.modelnet.network.HttpClient
import com.miloyu.modelnet.network.HttpClient.Companion.instance
import com.miloyu.modelnet.network.service.IApiService
import com.miloyu.modelnet.network.tools.RxUtils
import com.miloyu.modelnet.response.*
import com.sx.micowell.framework.adapter.binding.bean.FragmentTitleArgument
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.entity.PlanSettingBean
import com.sx.micowell.framework.entity.event.RefreshTrainEvent
import io.reactivex.Observable
import io.reactivex.Single
import java.util.*
import java.util.function.Consumer
import java.util.function.Function
import java.util.stream.Collectors
import kotlin.collections.LinkedHashMap
import kotlin.streams.toList

/**
 * @Description
 * @Author 梁浩文
 * @Date 2021/7/27 15:19
 */
class TrainModel : BaseViewModel() {
    var urlOne = "/basics/category/list/"
    var type: Int = 0
    var planSelectData: MutableList<TrainListVO> = mutableListOf()             //计划选择

    var planSettingData: PlanSettingBean? = null                                 //动作分析选择

    var pieShow: MutableLiveData<Boolean> = MutableLiveData(true)

    var tabText = ObservableField("")         //当前选中的类型

    var fragmentListData: MutableLiveListData<FragmentTitleArgument> = MutableLiveListData()

    var trainStepSelectList: MutableLiveListData<TrainSelectData> =
        MutableLiveListData()  //一级分类的选中步骤

    var trainStepList: MutableLiveListData<TrainListBeanInfo> =
        MutableLiveListData()       //一级分类步骤 列表

    var trainOnList: MutableLiveListData<PieEntry> = MutableLiveListData()                  //一级分类图表

    var trainSecondList = mutableMapOf<Int, List<PieEntry>>()               //二级分类图表

    var loadSuccessEvent: MutableLiveData<Boolean> = MutableLiveData()

    var currentSelectSecondType = mutableListOf<Int>()//当前选中的二级分类类型 索引x

    var currentSelectOneType = mutableListOf<Int>()//当前选中的一级分类类型 索引x

    var trainActionId = mutableMapOf<String, String>()

    var currentSelectId: Int? = null

    //跑步数据
    var runLiveData: Date? = null     //跑步时间

    var runScenesLiveData: PlanSettingBean? = null //运动场景


    fun getSelectOneXById(id: Int): Int {
        trainOnList.value?.forEach {
            if (it.label.split("_")[1].toInt() == id) {
                return trainOnList.value!!.indexOf(it)
            }
        }
        return -1;
    }

    fun initFragment() {
        var builder = MutableLiveListData.Builder<FragmentTitleArgument>(fragmentListData)
        var arrayOf = arrayOf("力量", "跑步")
        for (i in 0..1) {
            builder.add(
                FragmentTitleArgument(
                    arrayOf[i], RouteManager.getInstance().getTrainStepFragment(
                        i + 1
                    )
                )
            )
        }
        builder.buildPost()
    }


    fun reqTrainList() {
       HttpClient.instance.create(IApiService::class.java)
            .getCategoryList(type)
            .compose(RxUtils.compose())
            .subscribe(object : ApiResponse<TrainListBean>() {
            override fun success(data: TrainListBean?, msg: String?) {
                data?.let {
                    reqTrainSecondList(it.info)
                    trainStepList.postValue(it.info)
                    trainOnList.postValue(it.info.stream().map {
                        PieEntry(
                            1f,
                            "${it.categoryName}_${it.id}"
                        )
                    }.toList())
                }
            }

            override fun onFail(e: Throwable?, errorMsg: String?) {
            }

        })
    }

    fun reqTrainSecondList(trainListSecondBean: List<TrainListBeanInfo>) {
        trainListSecondBean?.let {
            var reqList =
                trainListSecondBean.stream()
                    .filter { (_, _, _, categoryParid) -> categoryParid == 0 }
                    .map {
                        HttpClient.instance.create(IApiService::class.java)
                            .getCategoryParentList(it.id)
                    }.toList()
            Observable.merge(reqList)
                .compose(RxUtils.compose())
                .doOnNext {
                    it?.data?.info?.let {
                        if (it.size > 0) {
                            if (it[0].categoryParid == 1018) {
                                for (trainListBeanInfo in it) {
                                    trainActionId[trainListBeanInfo.id.toString()] =
                                        trainListBeanInfo.curriculumType
                                }
                            }
                        }
                    }

                }
                .map {
                    it.data.info.stream()
                        .map {
                            PieEntry(
                                1f,
                                "${it.categoryName}_${it.id}&${it.categoryParid}&${it.categoryCmd}"
                            )
                        }
                        .toList()
                }
                .toList()
                .subscribe(io.reactivex.functions.Consumer {
                    it.forEach {
                        if (it?.size!! > 0) {
                            trainSecondList[it[0].label.split("&")[1].toInt()] = it
                        }
                        loadSuccessEvent.postValue(true)
                    }
                })
        }

    }


    override fun registerRxBus() {
        super.registerRxBus()
        "registerRxBus${type}".log()
        addSubscribe(RxBus.getDefault().toObservable(RefreshTrainEvent::class.java).subscribe {
            "registerRxBus".log()
            if (loadSuccessEvent.value == null) {
                reqTrainList()
            }
        })
    }

    fun getcategoryNames(): String {
        var actionId = mutableListOf<String>()
        var data = trainStepSelectList.getData(TrainSelectData(1018))
        data.child?.let {
            var split = it.toString().split(",")
            for (s in split) {
                var action = trainActionId.get(s) as String
                actionId.add(action)
            }
        }
        var joinToString = actionId.joinToString(separator = ",")
        joinToString.log()
        return joinToString
    }

}

